﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using System.Globalization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.DocumentManagement.DocumentSets;

using KoPortal.Sys;
using KoPortal.Sys.Data;
using KoPortal.Sys.Data.Axapta;
using KoPortal.Sys.Net;
using KoPortal.Sys.Metadata;

namespace JobCreateInDocs.Features.JobCreateInDocs
{
    [Guid("C8752CAC-1AF0-43C0-B2FE-137006A4D692")]
    public class JobCreateInDocs : SPJobDefinition
    {
        #region Propertys
        private string _DisplayName =
@"(Ko) Import new documents (bill), ver. 1.0.0.11";
        public override string DisplayName
        {
            get
            {
                return _DisplayName;
            }
        }
        private string _Description =
@"(Ko) Импорт новых накладных. Загружаются из AXAPTA через заданное время по таймеру. "
+ @"Настройка коннекта к базе и глубина выборки в днях находятся к глобальных настройках Ko";
        public override string Description
        {
            get
            {
                return _Description;
            }
        }
        #endregion Propertys
        #region Members
        string sUrl = "http://localhost";
        string sWeb = "/shops/";
        string sListName = "Первичные документы";
        #endregion #region Members
        #region Constructors
        public JobCreateInDocs() : base()
        {
            this.Title = "(Ko) Импорт новых накладных";
        }
        public JobCreateInDocs(string jobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(jobName, service, server, targetType)
        {
            this.Title = "(Ko) Импорт новых накладных";
        }
        public JobCreateInDocs(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "(Ko) Импорт новых накладных";
        }
        #endregion Constructors
        #region Common Methods
        static public string StringConvertName(String mName)
        {
            return mName.Replace("\"", "'"); ;
        }
        #endregion Common Methods
        #region Job Methods
        public Exception Execute(Guid contentDbId, string siteStr)
        {
            #region Members
            Exception ret = null;
            Exception err = null;
            int lcid = CultureInfo.CurrentCulture.LCID;
            string DomainNameStr = KoEnvironment.GetAppSetting("DomainName");
            int iAllRowsCount = 0;
            int iCurRow = 0;
            string errMsg = "";
            int ErrId = 0;
            int WarningLevel = 1;
            int RetCode = 0;
            DateTime dtStart = DateTime.Now;
            DateTime dtEnd = DateTime.Now;
            DateTime dtEndPointShop = DateTime.Now;
            DateTime dtEndPointSuplier = DateTime.Now;
            DateTime dtEndPointReceiptJour = DateTime.Now;
            DateTime dtLastSuccessfullyReceiptJour = new DateTime();
            DateTime dtLastSuccessfullyShops = new DateTime();
            DateTime dtLastSuccessfullySuplier = new DateTime();
            #endregion Members
            #region JobCreateInDocs
            KoEnvironment.Log_Add("Job", "JobCreateInDocs", "Start", DateTime.Now.ToString()
                , "", 0, 1, 0, 0);
            if (NetInfo.MachineName == "ws0279"
                || (DateTime.Now.Hour >= 7 && DateTime.Now.Hour <= 23))
            {
                try
                {
                    #region Init (Start)
                    //_____________________________________
                    // Get job lost finale time
                    err = JobCreateInDocsMethods.GetLastsuccessfullyDateTime(ref dtLastSuccessfullyReceiptJour);
                    if (err == null)
                        err = JobCreateInDocsMethods.GetLastsuccessfullyShopsDateTime(ref dtLastSuccessfullyShops);
                    if (err == null)
                        err = JobCreateInDocsMethods.GetLastsuccessfullySuplierDateTime(ref dtLastSuccessfullySuplier);
                    #region If Error
                    if (err != null)
                    {
                        ret = err;
                        errMsg = err.Message;
                        ErrId = 1;
                        RetCode = 1;
                        KoEnvironment.Log_Add("Job", "JobCreateInDocs", "Error", errMsg
                            , "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                        goto TheEndExecute;
                    }
                    #endregion If Error
                    #endregion Init (Start)
                    #region Process
                    if (err == null)
                    {
                        #region Verify Metadata structure Shops
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            if (MetadataHelper.ExistTermSet(siteStr, "Магазины") == false)
                            {
                                err = new Exception("Error - Verify Metadata structure - Shops");
                            }
                        });
                        #region If Error
                        if (err != null)
                        {
                            ret = err;
                            errMsg = err.Message;
                            ErrId = 1;
                            RetCode = 1;
                            KoEnvironment.Log_Add("Job", "JobCreateInDocs", "Error - Verify Metadata structure - Shops"
                                , errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                            goto TheEndExecute;
                        }
                        #endregion If Error
                        #endregion Verify Metadata structure
                        #region Verify Metadata structure Suplier
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            if (MetadataHelper.ExistTermSet(siteStr, "Поставщики") == false)
                            {
                                err = new Exception("Error - Verify Metadata structure - Suplier");
                            }
                        });
                        #region If Error
                        if (err != null)
                        {
                            ret = err;
                            errMsg = err.Message;
                            ErrId = 1;
                            RetCode = 1;
                            KoEnvironment.Log_Add("Job", "JobCreateInDocs", "Error - Verify Metadata structure - Suplier"
                                , errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                            goto TheEndExecute;
                        }
                        #endregion If Error
                        #endregion Verify Metadata structure
                        #region Get ReceiptJour DataTable
                        DataTable tbl = new DataTable();
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            err = DBReceiptJour.GetDataByDataTime(ref tbl, dtLastSuccessfullyReceiptJour);
                        });
                        #region If Error
                        if (err != null)
                        {
                            ret = err;
                            errMsg = err.Message;
                            ErrId = 1;
                            RetCode = 1;
                            KoEnvironment.Log_Add("Job", "JobCreateInDocs", "Error", errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                            goto TheEndExecute;
                        }
                        #endregion If Error
                        #region Last DT Convert
                        if (tbl.Rows.Count > 0)
                        {
                            if (tbl.Rows[0]["ModifiedDate"] != DBNull.Value)
                            {
                                dtEndPointReceiptJour =
                                    DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                        tbl.Rows[0]["ModifiedDate"], (int)tbl.Rows[0]["ModifiedTime"]);
                            }
                        }
                        else
                            dtEndPointReceiptJour = dtLastSuccessfullyReceiptJour;
                        #endregion Last DT Convert
                        #endregion Get ReceiptJour DataTable
                        #region Get Shops DataTable
                        DataTable tblShops = new DataTable();
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            err = DBShops.GetDataByDataTime(ref tblShops, dtLastSuccessfullyShops);
                        });
                        #region If Error
                        if (err != null)
                        {
                            ret = err;
                            errMsg = "DBShops.GetDataByDataTime() : Msg : " + err.Message;
                            ErrId = 1;
                            RetCode = 1;
                            KoEnvironment.Log_Add("Job", "JobCreateInDocs", "Error"
                                , errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                            goto TheEndExecute;
                        }
                        #endregion If Error
                        #region Last DT Convert
                        if (tblShops.Rows.Count > 0)
                        {
                            if (tblShops.Rows[0]["ModifiedDate"] != DBNull.Value)
                            {
                                dtEndPointShop =
                                    DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                        tblShops.Rows[0]["ModifiedDate"], (int)tblShops.Rows[0]["ModifiedTime"]);
                            }
                        }
                        else
                            dtEndPointShop = dtLastSuccessfullyShops;
                        #endregion LastDT Convert
                        #endregion Get Shops DataTable
                        #region Get Suplier DataTable
                        DataTable tblSuplier = new DataTable();
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            err = DBSuplier.GetDataByDataTime(ref tblSuplier, dtLastSuccessfullySuplier);
                        });
                        #region If Error
                        if (err != null)
                        {
                            ret = err;
                            errMsg = "DBSuplier.GetDataByDataTime() : Msg : " + err.Message;
                            ErrId = 1;
                            RetCode = 1;
                            KoEnvironment.Log_Add("Job", "JobCreateInDocs", "Error"
                                , errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                            goto TheEndExecute;
                        }
                        #endregion If Error
                        #region Last DT Convert
                        if (tblSuplier.Rows.Count > 0)
                        {
                            if (tblSuplier.Rows[0]["ModifiedDate"] != DBNull.Value)
                            {
                                dtEndPointSuplier =
                                    DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                        tblSuplier.Rows[0]["ModifiedDate"], (int)tblSuplier.Rows[0]["ModifiedTime"]);
                            }
                        }
                        else
                            dtEndPointSuplier = dtLastSuccessfullySuplier;
                        #endregion LastDT Convert
                        #endregion Get Suplier DataTable
                        #region Read Data
                        iAllRowsCount += tbl.Rows.Count + tblShops.Rows.Count + tblSuplier.Rows.Count;
                        iCurRow = 0;
                        //___________
                        // Metadata :
                        // Shops :
                        #region Shops
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            using (SPSite site = new SPSite(siteStr))
                            {
                                foreach (DataRow row in tblShops.Rows)
                                {
                                    // Job Progress :
                                    iCurRow++;
                                    this.UpdateProgress((int)(iCurRow * 100 / iAllRowsCount));
                                    if (row["ID"] == DBNull.Value)
                                        continue;
                                    if (!MetadataHelper.ExistItem(site, "Магазины", row["ID"].ToString(), lcid))
                                    {
                                        #region Insert
                                        err = MetadataSyncBase.Insert(
                                                site
                                            , "Магазины"
                                            , row["ID"].ToString()
                                            , StringConvertName(row["NAME"].ToString())
                                            , StringConvertName(row["Addr"].ToString())
                                            , lcid);
                                        #endregion Insert
                                        #region If Error
                                        if (err != null)
                                        {
                                            ret = err;
                                            errMsg = err.Message
                                                + " ; ( LoginName -" + site.RootWeb.CurrentUser.LoginName + ")";
                                            ErrId = 2;
                                            RetCode = 2;
                                            KoEnvironment.Log_Add("Sync", "MetadataSyncShops", "Error", errMsg
                                                , "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                                            break;
                                        }
                                        #endregion If Error
                                        // CreateLineLog("Add Shop : " + StringConvertName(reader["NAME"].ToString()));
                                    }
                                    #region Last DT Convert
                                    if (row["ModifiedDate"] != DBNull.Value)
                                    {
                                        DateTime dtTmp = DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                                row["ModifiedDate"], (int)row["ModifiedTime"]);
                                        if (dtTmp > dtEndPointShop)
                                            dtEndPointShop =
                                                DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                                    row["ModifiedDate"], (int)row["ModifiedTime"]);
                                    }
                                    #endregion LastDT Convert
                                } // foreach
                            } // using (SPSite site = new SPSite(@"http://localhost"))
                        });
                        if(err != null)
                            goto TheEndExecute;
                        #endregion Shops
                        // Company - Suplier
                        #region Suplier
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            using (SPSite site = new SPSite(siteStr))
                            {
                                foreach (DataRow row in tblSuplier.Rows)
                                {
                                    // Job Progress :
                                    iCurRow++;
                                    this.UpdateProgress((int)(iCurRow * 100 / iAllRowsCount));
                                    if (row["ID"] == DBNull.Value)
                                        continue;
                                    if (!MetadataHelper.ExistItem(site, "Поставщики", row["ID"].ToString(), lcid))
                                    {
                                        #region Insert
                                        err = MetadataSyncBase.Insert(
                                              site
                                            , "Поставщики"
                                            , row["ID"].ToString()
                                            , StringConvertName(row["NAME"].ToString())
                                            , StringConvertName(row["FullName"].ToString())
                                            , lcid);
                                        #endregion Insert
                                        #region If Error
                                        if (err != null)
                                        {
                                            ret = err;
                                            errMsg = err.Message;
                                            ErrId = 2;
                                            RetCode = 2;
                                            KoEnvironment.Log_Add("Sync", "MetadataSyncSuplier", "Error", errMsg
                                                , "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                                            break;
                                        }
                                        #endregion If Error
                                    }
                                    #region Last DT Convert
                                    if (row["ModifiedDate"] != DBNull.Value)
                                    {
                                        DateTime dtTmp = DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                                row["ModifiedDate"], (int)row["ModifiedTime"]);
                                        if (dtTmp > dtEndPointSuplier)
                                            dtEndPointSuplier =
                                                DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                                    row["ModifiedDate"], (int)row["ModifiedTime"]);
                                    }
                                    #endregion LastDT Convert
                                } // foreach
                            } // using (SPSite site = new SPSite(@"http://localhost"))
                        });
                        if (err != null)
                            goto TheEndExecute;
                        #endregion Suplier
                        // Documents :
                        #region Documents
                        foreach (DataRow row in tbl.Rows)
                        {
                            // Job Progress :
                            iCurRow++;
                            this.UpdateProgress((int)(iCurRow * 100 / iAllRowsCount));
                            if (!JobCreateInDocsMethods.inExistsDocs(
                                row["PurchId"].ToString()
                                + "("
                                + JobCreateInDocsMethods.TRIMInvoice(row["PackingSlipId"].ToString()) + ")"
                                )
                                )
                            {
                                // Insert New Item
                                SPListItem mItem =
                                    JobCreateInDocsMethods.InsertDocs(
                                        row["PurchId"].ToString()
                                        + "("
                                        + JobCreateInDocsMethods.TRIMInvoice(row["PackingSlipId"].ToString()) + ")"
                                        , DomainNameStr + "\\" + row["NETWORKALIAS"].ToString());

                                if (mItem != null)
                                {
                                    mItem["Номер накладной"] =
                                        JobCreateInDocsMethods.TRIMInvoice(row["PackingSlipId"].ToString());
                                    mItem["Дата комплекта"] = row["WDate"].ToString();

                                    Term mTerm;
                                    mTerm = JobCreateInDocsMethods.inExistsLib("Поставщики", row["VenderID"].ToString(), lcid);
                                    if (mTerm != null)
                                    {
                                        JobCreateInDocsMethods.UpdateListItemTermColumn(mItem, "Поставщик", mTerm);
                                    }
                                    mTerm = JobCreateInDocsMethods.inExistsLib("Магазины", row["InventLocationid"].ToString(), lcid);
                                    if (mTerm != null)
                                    {
                                        JobCreateInDocsMethods.UpdateListItemTermColumn(mItem, "Магазин", mTerm);
                                    }
                                    JobCreateInDocsMethods.SetRoleItem(mItem, row["Name"].ToString());
                                    mItem.SystemUpdate();
                                    mItem.Update();
                                    //CreateLineLog(
                                    //    "Add Row Doc : " + row["PurchId"].ToString()
                                    //    + "(" + row["PackingSlipId"].ToString() + ")"
                                    //    , mTerm);
                                }
                                else // mItem != null
                                {
                                    //Term mTerm;
                                    //mTerm = JobCreateInDocsMethods.inExistsLib("Магазины", row["InventLocationid"].ToString(), lcid);
                                    //if (mTerm != null)
                                    //{
                                    // !!! mItem == null !!!
                                    //JobCreateInDocsMethods.UpdateListItemTermColumn(mItem, "Магазин", mTerm);
                                    //}

                                    // Error , not inserted item
                                    #region If Error
                                    //ret = err;
                                    errMsg = "Doc not inserted - " + row["PurchId"].ToString() + "("
                                        + JobCreateInDocsMethods.TRIMInvoice(row["PackingSlipId"].ToString()) + ")"
                                        + DomainNameStr + "\\" + row["NETWORKALIAS"].ToString();
                                    ErrId = 2;
                                    RetCode = 2;
                                    KoEnvironment.Log_Add("Sync", "JobCreateInDocs", "Documents Sync Error", errMsg
                                        , "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                                    // goto TheEndExecute;
                                    continue;
                                    #endregion If Error
                                }
                            } // if exist
                            #region Last DT Convert
                            if (row["ModifiedDate"] != DBNull.Value)
                            {
                                DateTime dtTmp = DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                    row["ModifiedDate"], (int)row["ModifiedTime"]);
                                if (dtTmp > dtEndPointReceiptJour)
                                    dtEndPointReceiptJour =
                                        DBHelper.MakeDateTimeFromAxaptaFields((DateTime)
                                            row["ModifiedDate"], (int)row["ModifiedTime"]);
                            }
                            #endregion LastDT Convert
                        } // foreach
                        #endregion Documents
                        #endregion Read Data
                    }
                    #endregion Process
                    #region If Error
                    if (err != null)
                    {
                        ret = err;
                        errMsg = err.Message;
                        ErrId = 2;
                        RetCode = 2;
                        KoEnvironment.Log_Add("Job", "JobCreateInDocs", "Error", errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                        goto TheEndExecute;
                    }
                    #endregion End If Error
                    #region Save Final date time
                    dtEnd = DateTime.Now;
                    if (err == null)
                    {
                        err = JobCreateInDocsMethods.SetLastsuccessfullyDateTime(dtEndPointReceiptJour);
                        if (err == null)
                            err = JobCreateInDocsMethods.SetLastsuccessfullyShopsDateTime(dtEndPointShop);
                        if (err == null)
                            err = JobCreateInDocsMethods.SetLastsuccessfullySuplierDateTime(dtEndPointSuplier);
                    }
                    #endregion Save Final date time
                }
                #region Catch
                catch (Exception ex)
                {
                    ret = new Exception(ex.Message, err);
                    errMsg = err.Message;
                    ErrId = 1;
                    RetCode = 1;
                    KoEnvironment.Log_Add("Job", "JobCreateInDocs", "Error", errMsg, "", ErrId, WarningLevel, RetCode, iAllRowsCount);
                }
                #endregion Catch
            } // if()
            #region End JobCreateInDocs
        TheEndExecute:
            KoEnvironment.Log_Add("Job", "JobCreateInDocs", "Stop", DateTime.Now.ToString()
                , "", ErrId, WarningLevel, RetCode, iAllRowsCount);
            #endregion End
            #endregion JobCreateInDocs
            #region Clear Logs
            DateTime dtFrom = DateTime.Now;
            TimeSpan span = new TimeSpan(90, 0, 0, 0);
            dtFrom = dtFrom - span;
            err = DBSPLog.Delete(dtFrom);
            #endregion Clear Logs
            return ret;
        }
        public override void Execute(Guid contentDbId)
        {
            Exception err = Execute(contentDbId, "http://localhost");
        }
        #endregion Job Methods
    }
}

